package com.bezdelnick.forum.web.page;

import com.bezdelnick.forum.domain.ModelBean;
import com.bezdelnick.forum.domain.Question;
import com.bezdelnick.forum.domain.Subtype;
import com.bezdelnick.forum.domain.Type;
import com.bezdelnick.forum.service.ForumService;
import com.bezdelnick.forum.web.component.LinkWithText;
import com.bezdelnick.forum.web.component.QuestionsListView;
import com.bezdelnick.forum.web.model.NavigationTreeModel;
import com.bezdelnick.forum.web.page.template.AdminMainMenuAndLeftMenuTemplate;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.tree.BaseTree;
import org.apache.wicket.markup.html.tree.LinkTree;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: User
 * Date: 10.08.12
 * Time: 14:13
 * To change this template use File | Settings | File Templates.
 */
@AuthorizeInstantiation("ROLE_ADMIN")
public class ModeratorPage extends AdminMainMenuAndLeftMenuTemplate {
    private static final Logger LOGGER = LoggerFactory.getLogger(ModeratorPage.class);
    private static final String TREE_ROOT_NAME = "Types answers";

    public static final String ACTION_EDIT = "edit";
    public static final String ACTION_REMOVE = "remove";

    public List<Question> questions;

    @SpringBean
    @SuppressWarnings("unused")
    private ForumService forumService;

    public ModeratorPage() {
        //
    }

    public ModeratorPage(PageParameters parameters) {
        if (!(parameters.get("action").equals(null) || parameters.get("id").equals(null))) {

            String deliveryAction = parameters.get("action").toString();
            Long deliveryId = parameters.get("id").toLong();

            /* If question exists in database we can edit or delete it */
            if (forumService.getQuestionDao().getQuestionById(deliveryId) != null) {

                if (deliveryAction.equals(ACTION_EDIT)) {
                    PageParameters pageParameters = new PageParameters();
                    pageParameters.add("id", deliveryId);
                    AddQuestionPage addQuestionPage = new AddQuestionPage();
                    redirectToInterceptPage(addQuestionPage);
                } else if (deliveryAction.equals(ACTION_REMOVE)) {
                    /* At first delete all answers which related with current question */
                    forumService.getAnswerDao().deleteAnswersByQuestionId(deliveryId);
                    /* At second delete question */
                    forumService.getQuestionDao().deleteQuestion(deliveryId);
                }
            }

            this.getPageParameters().remove("action");
            this.getPageParameters().remove("id");
        }
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        this.questions = forumService.getQuestionDao().loadQuestions();
        final QuestionsListView questionsListView = new QuestionsListView("list_questions", this.questions, ForumService.MODE.ADMIN);

        // add menu component
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new ModelBean(TREE_ROOT_NAME));
        NavigationTreeModel navigationTreeModel = new NavigationTreeModel(rootNode);

        BaseTree navigationTree = new LinkTree("menu", navigationTreeModel) {
            @Override
            protected void onNodeLinkClicked(Object node, BaseTree tree, AjaxRequestTarget target) {
                super.onNodeLinkClicked(node, tree, target);

                TreeNode _node = (TreeNode) node;

                if (!_node.isLeaf()) {
                    if (!_node.toString().equals(TREE_ROOT_NAME)) {
                        Type type = forumService.getTypeDao().getTypeByName(_node.toString());
                        if (type != null) {
                            questions = forumService.getQuestionDao().loadQuestionsByTypeId(type.getId());
                        }
                    } else {
                        questions = forumService.getQuestionDao().loadQuestions();
                    }

                    tree.updateTree(target);
                } else {
                    Subtype subtype = forumService.getSubtypeDao().getSubtypeByName(_node.toString());
                    if (subtype != null) {
                        questions = forumService.getQuestionDao().loadQuestionsBySubtypeId(subtype.getId());
                    }
                }

                questionsListView.prepareForRender();
            }
        };

        add(navigationTree);
        navigationTree.getTreeState().expandAll();

        // add body component
        add(new LinkWithText("sort_1", "#", "Sort 1"));
        add(new LinkWithText("sort_2", "#", "Sort 2"));
        add(new LinkWithText("sort_3", "#", "Sort 3"));

        questions = forumService.getQuestionDao().loadQuestions();

        add(questionsListView);
    }
}
